JSON IN JAVASCRIPT
JSON means JavaScript Object Notation.
It is a modern text format for storing and transferring structured data.
You will learn:
- what JSON is
- how JSON is different from a JavaScript object
- what data types JSON can store
- how
JSON.stringify()works - how
JSON.parse()works - what happens with functions
- how to handle JSON parsing errors with
try...catch - the difference between parsing errors and runtime errors
1. What is JSON?
JSON is often used for sending data to a server, receiving data from a server, storing data in local storage, and saving structured text data in files.
Important idea:
JSON is not a JavaScript object.
JSON is a string representation of data.
Diagram 1. Main idea of JSON
JavaScript object
↓ convert to text
JSON string
↓ parse back
JavaScript value
JavaScript objects can be converted into JSON text, and JSON text can be converted back into JavaScript data.
2. Example of JSON
{
"name": "Josh",
"weight": 175,
"age": 30,
"eyecolor": "brown",
"isHappy": true,
"cars": ["Chevy", "Honda"],
"favoriteBook": {
"title": "The Last Kingdom",
"author": "Bernard Cornwell",
"rating": 8.38
}
}
This looks similar to a JavaScript object, but it follows stricter rules.
3. JSON rules
JSON syntax is similar to an object, but there are important rules:
- keys must always be strings
- keys must always use double quotes
- string values must also use double quotes
- numbers can be integers or decimals, including negative numbers
- booleans
trueandfalseare written like in JavaScript - there is no comma after the last property
nullis allowedundefinedis not allowed- functions are not allowed
Diagram 2. JSON rules
JSON rules
│
├─ keys in double quotes
├─ strings in double quotes
├─ no trailing comma
├─ null is allowed
├─ undefined is not allowed
└─ functions are not allowed
These rules are very important because even one small mistake can make JSON invalid.
4. What data types can JSON store?
JSON can store:
- numbers
- strings
- booleans
- arrays
- objects
null
JSON cannot store:
undefined- functions
Diagram 3. Allowed vs not allowed
Allowed in JSON:
number
string
boolean
array
object
null
Not allowed in JSON:
undefined
function
5. Example of invalid JSON
Look at this code:
{
username: "Jacob",
age: 32,
}
This is not valid JSON.
- keys are not in double quotes
- there is a comma after the last property
Diagram 4. Why this is not valid JSON
{
username: "Jacob",
age: 32,
}
Problems:
1. username is not in double quotes
2. last property has trailing comma
6. Converting JavaScript data to JSON
To convert JavaScript data into JSON, use:
JSON.stringify(value)
This method takes a JavaScript value and returns a JSON string. The value can be a number, boolean, null, array, or object.
Diagram 5. JSON.stringify()
JavaScript value
↓
JSON.stringify(...)
↓
JSON string
After conversion, the result is text, not a normal JavaScript object anymore.
7. Example with an object
const dog = {
name: "Mango",
age: 3,
isGoodBoy: true,
};
const json = JSON.stringify(dog);
console.log(json); // '{"name":"Mango","age":3,"isGoodBoy":true}'
The result of JSON.stringify() is a string that contains valid JSON. This string can be saved, sent over the network, or written to storage.
Diagram 6. Object to JSON string
dog object
│
├─ name: "Mango"
├─ age: 3
└─ isGoodBoy: true
JSON.stringify(dog)
↓
'{"name":"Mango","age":3,"isGoodBoy":true}'
8. What happens with simple values?
Number
console.log(JSON.stringify(32)); // "32"
Boolean
console.log(JSON.stringify(true)); // "true"
The result is a JSON string version of the value.
Diagram 7. Simple conversion
32
↓ stringify
"32"
true
↓ stringify
"true"
9. What happens with functions?
Functions cannot be stored in JSON.
If an object contains methods, those methods are ignored during conversion.
const dog = {
name: "Mango",
age: 3,
isGoodBoy: true,
bark() {
console.log("Woof!");
},
};
const json = JSON.stringify(dog);
console.log(json); // '{"name":"Mango","age":3,"isGoodBoy":true}'
Here the bark() method is not included in the JSON result.
Diagram 8. Methods are ignored
Object
│
├─ name
├─ age
├─ isGoodBoy
└─ bark() ← function
JSON.stringify(...)
↓
function is ignored
JSON is made only for data, not for behavior.
10. What if you stringify a function directly?
If you try to convert a function itself into JSON, the result is undefined.
const json = JSON.stringify(() => console.log("Well, this is awkward"));
console.log(json); // undefined
This happens because functions are not valid JSON data.
11. Parsing JSON back into JavaScript
To convert JSON text back into JavaScript data, use:
JSON.parse(value)
This method takes a JSON string and returns a real JavaScript value.
Diagram 9. JSON.parse()
JSON string
↓
JSON.parse(...)
↓
JavaScript value
12. Example with simple values
console.log(JSON.parse("5")); // 5
console.log(JSON.parse("false")); // false
console.log(JSON.parse("null")); // null
Here the input is text, but the result is real JavaScript data.
13. Example with an object
const json = '{"name":"Mango","age":3,"isGoodBoy":true}';
const dog = JSON.parse(json);
console.log(dog); // {name: "Mango", age: 3, isGoodBoy: true}
console.log(dog.name); // "Mango"
After parsing, dog becomes a normal JavaScript object, so you can access its properties as usual.
Diagram 10. JSON string to object
'{"name":"Mango","age":3,"isGoodBoy":true}'
↓ JSON.parse(...)
{ name: "Mango", age: 3, isGoodBoy: true }
14. What happens with invalid JSON?
If you pass invalid JSON to JSON.parse(), JavaScript throws an error.
That means the script stops at that place, and code after the error does not run.
const data = JSON.parse("Well, this is awkward");
console.log("You will not see this log");
This causes an error because a plain text string like that is not valid JSON.
15. Another invalid JSON example
const data = JSON.parse('{username: "Mango"}'); // Error
console.log("You will not see this log");
This is invalid because the key username is not in double quotes.
Diagram 11. Invalid JSON result
Invalid JSON string
↓
JSON.parse(...)
↓
error
↓
script stops here
16. How to handle parsing errors
To safely handle parsing errors, use try...catch.
This lets the script continue working even if parsing fails.
Basic structure
try {
// code that may throw an error
} catch (error) {
// error handling
}
Diagram 12. try...catch
try
↓
run risky code
If no error
↓
catch is skipped
If error happens
↓
jump to catch
↓
handle the error
This is the safest way to work with JSON that may be invalid.
17. Example of safe JSON parsing
try {
const data = JSON.parse("Well, this is awkward");
} catch (error) {
console.log(error.name); // "SyntaxError"
console.log(error.message); // Unexpected token W in JSON at position 0
}
console.log("This is fine, we handled parsing error in try...catch");
Here, JSON.parse() throws an error, catch handles the error, and the script continues after the try...catch block.
Diagram 13. Safe parsing flow
parse JSON
↓
error happens
↓
catch handles error
↓
script continues
18. The error object
Inside catch, the variable error contains information about the problem.
Useful properties are:
error.name- type of errorerror.message- explanation of the errorerror.stack- call stack, useful for debugging
Diagram 14. Error object
error
│
├─ name
├─ message
└─ stack
For JSON parsing errors, error.name is usually "SyntaxError".
19. Why use try...catch with JSON?
JSON may come from a server, local storage, another file, or user input. It might be broken or invalid.
So the main reason to use try...catch is:
to stop the script from crashing if parsing fails
This is exactly why it is used in practice.
20. Parsing errors vs runtime errors
The lesson also explains an important difference between two phases.
Evaluation phase
This is when JavaScript first reads the code and checks whether it can run at all.
At this stage, JavaScript looks for syntax mistakes. If there is a syntax error, execution does not even start. These are called parsing errors.
Runtime phase
This is when the script is actually running.
At this stage, JavaScript executes functions, expressions, and variable lookups. Errors here are called runtime errors.
Diagram 15. Two phases
1. Evaluation phase
↓
check syntax
2. Runtime phase
↓
run the code
21. Example of a parsing error
console.log("This message will not appear in the console");
cos value = 5;
This contains a syntax mistake: cos instead of const.
Because of that:
- JavaScript finds the mistake during the evaluation phase
- execution never starts
- the console log does not run at all
Diagram 16. Parsing error
Code has syntax error
↓
evaluation phase fails
↓
runtime does not start
↓
script does not run
22. Important rule about try...catch
try...catch catches runtime errors, not syntax errors that stop the code before execution starts.
That means your code must already be syntactically valid for try...catch to work.
Diagram 17. What try...catch can catch
Syntax error before runtime
↓
try...catch cannot help
Runtime error during execution
↓
try...catch can catch it
This is very important for beginners:
try...catch does not fix broken syntax
23. Easy memory rules
JSON = text format for structured data
JSON.stringify() = JavaScript → JSON string
JSON.parse() = JSON string → JavaScript
Functions in JSON = not allowed
Invalid JSON + JSON.parse() = error
try...catch = safe error handling
24. Quick summary
- JSON is a text format for storing and transferring structured data.
- JSON is not a JavaScript object; it is its string representation.
- JSON requires double quotes for keys and strings.
- JSON can store numbers, strings, booleans, arrays, objects, and
null. - JSON cannot store
undefinedor functions. JSON.stringify()converts JavaScript values into JSON strings.JSON.parse()converts JSON strings into JavaScript values.- Invalid JSON causes
JSON.parse()to throw an error. try...catchis used so the script does not crash when parsing fails.try...catchcatches runtime errors, not syntax errors that prevent execution from starting.
25. Final conclusion
If you understand these ideas:
JSON format
valid JSON rules
JSON.stringify()
JSON.parse()
functions are ignored
try...catch
runtime vs parsing errors
then you already have a strong foundation for working with JSON in JavaScript.
This topic is extremely important because JSON is used everywhere in real development:
- APIs
- servers
- local storage
- files
- configuration data